package linkedhomework;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-01-05
 * Time: 21:58
 */

//https://leetcode.cn/problems/intersection-of-two-linked-lists/submissions/393237609/
class ListNode1 {
    int val;
    ListNode1 next;

    ListNode1(int x) {
        val = x;
        next = null;
    }
}


public class Solution {
    public ListNode1 getIntersectionNode(ListNode1 headA, ListNode1 headB) {
        int len1 = 0;//设定len1最长
        int len2 = 0;
        ListNode1 curA = headA;
        ListNode1 curB = headB;
        while (curA != null) {
            len1++;
            curA = curA.next;
        }
        while (curB != null) {
            len2++;
            curB = curB.next;
        }
        if (curA != curB) {
            return null;
        }
        curA = headA;
        curB = headB;
        int temp = len1 - len2;
        if (temp > 0) {//A比较长
            while (temp != 0) {
                curA = curA.next;
                temp--;
            }
        } else {//B比较长
            temp = len2 - len1;
            while (temp != 0) {
                curB = curB.next;
                temp--;
            }
        }
        while (curA != null) {
            if (curA == curB) {
                return curA;
            }
            curA = curA.next;
            curB = curB.next;
        }
        return null;
    }
}
